package com.ln.prac.base.m202206.d17;

/**
 * <pre>
 *  单例 - 懒汉式 -线程安全 - 双检
 * </pre>
 *
 * @Author zhangj
 * @Date 2022/6/17 23:46
 */
public class Singleton {

    private Singleton() {
    }

    private static volatile Singleton instance;

    public static Singleton getInstance() {
        // 第一次判断，如果instance 不为null，不进入抢锁阶段，直接返回实例
        if(instance == null) {
            synchronized (Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(getInstance());
            }).start();
        }

    }

}
